#!/bin/bash
#
#  Copyright 2022-2024 Intel Corporation.
#
#  SPDX-License-Identifier: BSD-2-Clause-Patent
#
# A git hook to validate and correct the copyright date in source files.

_print_githook_header "Copyright"
if [ -e .git/MERGE_HEAD ]; then
    echo "Merge commit. Skipping"
    exit 0
fi

echo "Updating copyright headers"

regex='(^[[:blank:]]*[\*/]*.*)((Copyright[[:blank:]]*)([0-9]{4})(-([0-9]{4}))?)([[:blank:]]*(Intel.*$))'
year=$(date +%Y)
errors=0
targets=(
    # Entries with wildcard.  These must be first and start with '*' or
    # older versions of git will return files that were not changed.
    '*.c'
    '*.h'
    '*.go'
    '*.py'
    '*.proto'
    '*.java'
    '*.yml'
    '*.yaml'
    '*.sh'
    '*.bash'
    '*Dockerfile*'
    '*README*'
    '*LICENSE*'
    '*NOTICE*'
    '*.txt'
    '*.md'
    # Entries without a wildcard
    'Makefile'
    'Jenkinsfile'
    'SConscript'
    'SConstruct'
    'copyright'
    '.env'
)

if [ -z "$files" ]; then
    files=$(git diff "$TARGET" --cached --diff-filter=AM --name-only -- "${targets[@]}")
else
    echo "  Checking against custom files"
fi

os=$(uname -s)

. utils/githooks/git-version.sh

for file in $files; do
    if [[ "$file" == *vendor* ]] || [[ "$file" == *pb.go ]]    ||
       [[ "$file" == *_string.go ]] || [[ "$file" == *pb-c* ]] ||
       { [ "$git_vercode" -ge 2030000 ] &&
         [ "$(git diff --cached -I Copyright "$file")" = '' ]; }; then
        continue
    fi
    read -r y1 y2 <<< "$(sed -nre "s/^.*$regex.*$/\4 \6/p" "$file")"
    if [[ -z $y1 ]] ; then
        echo "  Copyright Information not found in: $file"
        errors=$((errors + 1))
    elif [[ $y1 -ne $year && $year -ne $y2 ]] ; then
        git reset "$file" || (echo "  Unable to un-stage $file" && exit 1)
        if [ "$os" == 'Linux' ]
        then
            sed -i -re "s/$regex/\1Copyright $y1-$year \8/" "$file"
        else
            sed -i '' -re "s/$regex/\1Copyright $y1-$year \8/" "$file"
        fi

        git add "$file" || (echo "  Unable to re-stage $file" && exit 1)
    fi
done
[[ $errors = 0 ]] || (echo "  $errors errors while checking/fixing copyrights.")
